#include "banana.h"
#include <QDebug>

Banana::Banana()
{
    scoreValue = 1 + rand() % 3;
    initialize();
}

Banana::Banana(int score)
{
    scoreValue = score;
    initialize();
}

void Banana::initialize()  // set scoreValue before calling this
{
    // THIS WOULD BE FOR UNIFORM DISTRIBUTION OF FALLING BANANAS
    //    rect = QRect(BANANA_DISTANCE_FROM_BORDER + rand() %
    //                 (WORLD_WIDTH - 2 * BANANA_DISTANCE_FROM_BORDER - BANANA_WIDTH + 1),
    //                0 - BANANA_HEIGHT, BANANA_WIDTH, BANANA_HEIGHT);

    // normal distribution
    std::random_device rand_dev;
    std::mt19937 generator(rand_dev());
    std::normal_distribution<double> distr((WORLD_WIDTH - BANANA_WIDTH) / 2, 100);
    int xCoord = distr(generator);

    // don't let bananas fall too close to the border:
    if (xCoord < BANANA_DISTANCE_FROM_BORDER || xCoord > WORLD_WIDTH - BANANA_WIDTH - BANANA_DISTANCE_FROM_BORDER)
    {
        xCoord = (WORLD_WIDTH - BANANA_WIDTH) / 2;
    }

    rect = QRect(xCoord, 0 - BANANA_HEIGHT, BANANA_WIDTH, BANANA_HEIGHT);

    type = BANANA;
    isMovable = true;
    isHitable = true;
    destroyLater = false;
    speed = MIN_BANANA_SPEED.at(_difficulty_) + rand()
            % (MAX_BANANA_SPEED.at(_difficulty_) - MIN_BANANA_SPEED.at(_difficulty_) + 1);
    lowestPos = GRASS_START + rand() % (GRASS_END - GRASS_START - BANANA_HEIGHT + 1);
    imageIndex = 0;

    if (scoreValue == 1) {
        image = BANANA1_FRAMES.at(imageIndex);
    } else if (scoreValue == 2) {
        image = BANANA2_FRAMES.at(imageIndex);
    } else if (scoreValue == 3) {
        image = BANANA3_FRAMES.at(imageIndex);
    }
}

void Banana::updatePosition()
{
    if (isMovable)
    {
        rect.translate(0, speed);

        if (rect.y() >= lowestPos)
        {
            isMovable = false;
            isHitable = false;
        }

        mObs->movedInModel(objId, rect.x(), rect.y());
    }
}

void Banana::nextImage()
{
    if (scoreValue == 1) {
        imageIndex = (imageIndex + 1) % BANANA1_FRAMES.size();
        image = BANANA1_FRAMES.at(imageIndex);
    } else if (scoreValue == 2) {
        imageIndex = (imageIndex + 1) % BANANA2_FRAMES.size();
        image = BANANA2_FRAMES.at(imageIndex);
    } else if (scoreValue == 3) {
        imageIndex = (imageIndex + 1) % BANANA3_FRAMES.size();
        image = BANANA3_FRAMES.at(imageIndex);
    }

    mObs->changedFrameInModel(objId, image);
}

Banana::~Banana()
{
    mObs->destroyedInModel(objId);
}

